#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPortInfo>
#include <QDateTime>
#include <QtCharts/QValueAxis>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_series(new QLineSeries)
{
    ui->setupUi(this);

    // 初始化串口管理器
    m_serialManager = SerialPortManager::instance();

    // 初始化界面
    setupChart();
    populatePorts();
    setupConnections();
}

void MainWindow::setupChart()
{
    m_chart = new QChart();
    m_chart->addSeries(m_series);
    m_chart->createDefaultAxes();

    QValueAxis *axisX = new QValueAxis;
    axisX->setRange(0, 60);
    axisX->setTitleText("Time (s)");

    QValueAxis *axisY = new QValueAxis;
    axisY->setRange(-20, 100);
    axisY->setTitleText("Temperature (°C)");

    m_chart->setAxisX(axisX, m_series);
    m_chart->setAxisY(axisY, m_series);

    ui->chartView->setChart(m_chart);
}

void MainWindow::populatePorts()
{
    ui->comboPort->clear();
    foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) {
        ui->comboPort->addItem(info.portName());
    }
}

void MainWindow::setupConnections()
{
    // 串口状态
    connect(m_serialManager, &SerialPortManager::portOpened,
            [this](bool success){
                ui->btnOpen->setText(success ? "Close" : "Open");
                logMessage(success ? "Port opened" : "Open failed");
            });

    // 数据接收
    connect(m_serialManager, &SerialPortManager::dataReceived,
            [this](const QByteArray &data){
                if(data.size() >= 5 && data.startsWith("TEMP:")) {
                    bool ok;
                    double temp = data.mid(5).trimmed().toDouble(&ok);
                    if(ok) updateTemperature(temp);
                }
                ui->textLog->append("RX: " + data.toHex(' '));
            });

    // 按钮事件
    connect(ui->btnOpen, &QPushButton::clicked, this, &MainWindow::onOpenClicked);
    connect(ui->btnSend, &QPushButton::clicked, this, &MainWindow::onSendClicked);
}

void MainWindow::onOpenClicked()
{
    if(m_serialManager->isOpen()) {
        m_serialManager->closePort();
    } else {
        m_serialManager->openPort(
            ui->comboPort->currentText(),
            ui->comboBaud->currentText().toInt()
            );
    }
}

void MainWindow::onSendClicked()
{
    QString cmd = ui->editCommand->text() + "\r\n";
    m_serialManager->writeData(cmd.toUtf8());
    ui->textLog->append("TX: " + cmd.trimmed());
}

void MainWindow::updateTemperature(double value)
{
    static qint64 startTime = QDateTime::currentMSecsSinceEpoch();
    qreal x = (QDateTime::currentMSecsSinceEpoch() - startTime) / 1000.0;

    m_series->append(x, value);
    ui->lcdTemp->display(value);

    // 保持显示最近60秒数据
    if(x > 60) {
        m_series->removePoints(0, m_series->count() - 1);
        m_chart->axisX()->setRange(x - 60, x);
    }
}

void MainWindow::logMessage(const QString &msg)
{
    QString timestamp = QDateTime::currentDateTime().toString("[hh:mm:ss] ");
    ui->textLog->append(timestamp + msg);
    ui->textLog->moveCursor(QTextCursor::End,QTextCursor::KeepAnchor);
}

MainWindow::~MainWindow()
{
    delete ui;
}
